#-*-coding:utf-8-*-

'''
# ----------------------------------------------------------------------------
#  Purpose:     用于实现函数的签名信息的获取

#  Author:      青衫少年春归也

#  Created:     20120.01.09

# ----------------------------------------------------------------------------
'''

import os
import sys
import inspect
import importlib


class PythonFunction():
    def parser_python_file(self, py_path: str):
        """
           获取RF 用户自定义关键字的参数信息
           :param
               suite_id: py文件suite
               tmp: 临时创建的目录
        """
        py_name = os.path.basename(py_path).replace(".py", "")
        sys.path.append(os.path.dirname(py_path))
        # 动态导入模块
        metaclass = importlib.import_module(py_name)
        info = {"name": py_name, "data": []}
        if inspect.ismodule(metaclass):
            for py_class in dir(metaclass):
                if not py_class.startswith("_"):
                    # 实例化类对象以及函数方法
                    py_instance = getattr(metaclass, py_class)
                    if inspect.isclass(py_instance):
                        info["data"].append(self._parser_python_class(py_instance, py_class))
                    elif inspect.isfunction(py_instance):
                        info["data"].append(self._parser_python_function(py_instance, py_class))
        sys.path.remove(os.path.dirname(py_path))
        return info


    def _parser_python_class(self, cls, cls_name: str):
        """
        解析Python类信息
        :param cls: 类名
        :return:
        """
        class_signature = inspect.signature(cls).parameters

        # 获取类的初始参数信息
        class_arguments = []
        for name, param in class_signature.items():
            if param.default and param.default != inspect._empty:
                class_arguments.append(f"{name}={param.default}")
            else:
                class_arguments.append(f"{name}")

        info = {"function": [], "class_name": cls_name, "class_doc": cls.__doc__, "class_arguments": class_arguments}

        # 获取类方法信息
        members = inspect.getmembers(cls)
        for member in members:
            if not member[0].startswith("_"):
                arguments = []
                signature = inspect.signature(member[1]).parameters
                for name, param in signature.items():
                    if param.default and param.default != inspect._empty:
                        arguments.append(f"{name}={param.default}")
                    else:
                        arguments.append(f"{name}")

                func_info = dict(function_name=member[0],
                                 function_doc=member[1].__doc__,
                                 function_arguments=arguments[1:])
                info["function"].append(func_info)
        return info


    def _parser_python_function(self, func: object, func_name: str) -> dict:
        """
        解析python函数对象的参数注释信息
            :param func: 函数对象
            :param func_name: 函数名
            :return: 解析结果字典
        """

        info = {"function": [], "class_name": "", "class_doc": "", "class_arguments": []}
        arguments = []
        func_signature = inspect.signature(func).parameters
        for name, param in func_signature.items():
            if param.default and param.default != inspect._empty:
                arguments.append(f"{name}={param.default}")
            else:
                arguments.append(f"{name}")
        info["function"].append(
            dict(function_name=func_name,
                 function_doc=func.__doc__,
                 function_arguments=arguments,
                 )
        )
        return info
